// pages/clockin/clockin.js
var QQMapWX = require('../../utils/qqmap-wx-jssdk');
var config = require("../../utils/config")
var qqmapsdk = new QQMapWX({
	key: config.qq_key // 必填
});
var util = require("../../utils/util");
var timeid;
const {
	http
} = require("../../utils/apiutils");

import {
	getMore
} from '../../utils/tools'
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		scrollH: 90,
		tabs: [{
				title: '考勤打卡',
				name: 1
			},
			{
				title: '打卡记录',
				name: 2
			}
		],
		tabActive: 1,
		active: 1,
		type: [],
		fileList: [],
		gwInfo: {},
		latitude: "",
		ds: "",
		time: util.formatTime(new Date()),
		longitude: "",
		dataList: [],
		lInfo: null,
		newTime: "",
		imgList: [],
		imgStr: [],
		spx: 0,
		jobData: null,
		dktype: {
			ds: true,
			tm: true,
		},
		sbsj: '',
		xbsj: '',
		pageNo: 1,
		hasMore: true,
		loading: false,
		pageSize: 10,
		recordList: [],
		workBc: [{
				status: 1,
				text: '白班'
			},
			{
				status: 2,
				text: '夜班'
			}
		],
		workBcIndex: 0,
		reddk: 0,
		dkrule: [],
		disabled: false,
		dktext: '打卡',
		getLocationTime: 0,
		dkworktype: 0,//   0 上班打卡  1 下班打卡
		workStartType:0,  // 0未打卡 1 已打卡
		workEndType: 0, // 0未打卡 1 已打卡
		copyData:null,
	},
	beforeRead(event) {
		const {
			file,
			callback
		} = event.detail;
		callback(file.type === 'image');
		const {
			fileList = []
		} = this.data;
		fileList.push({
			...file,
			url: file.url
		});
		this.setData({
			fileList
		});
	},
	onclicktHis: function () {
		let info = encodeURIComponent(JSON.stringify(this.data.gwInfo));
		wx.navigateTo({
			url: '/pages/calendar/calendar?info=' + info,
		})
	},
	onclickPz: function () {
		wx.navigateTo({
			url: '/pages/me/pages/photograph/photograph?type=xbsj',
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	getDateInfo() {
		var date = new Date()
		const hour = date.getHours() >= 10 ? date.getHours() : "0" + date.getHours()
		const minute = date.getMinutes() >= 10 ? date.getMinutes() : "0" + date.getMinutes()
		const second = date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds()
		return hour + ":" + minute + ":" + second;

	},

	onLoad: function (options) {
		var that = this;
		timeid = setInterval(function () {
			that.setData({
				newTime: that.getDateInfo()
			})
		}, 1000);
		let info = JSON.parse(decodeURIComponent(options.data))

		this.setData({
			gwInfo: info,
			copyData:options.data
		})
		var str = ""
		if (info.type == 1) {
			str = "到岗打卡"
		} else if (info.type == 2) {
			str = "工作打卡"
		} else if (info.type == 3) {
			str = "完成工作打卡"
		}
		wx.setNavigationBarTitle({
			title: str,
		})
		// this.formSubmit();
		// this.getclockInList()
		this.getJobData(this.data.gwInfo.jobId)
		this.getLocation()
		this.getRule()
	},
	getJobData: function (id) {

		var that = this;
		wx.showLoading({
			title: '加载中...',
		})
		http.getJobData(id,
			function (res) {
				wx.hideLoading()
				if (res.code == 0) {
					let db = res.data;
					that.setData({
						jobData: db
					})
				} else {
					wx.showToast({
						title: res.message,
						icon: "none",
					})
				}
			},
			function (err) {
				wx.hideLoading()
			})
	},
	getclockInList: function () {
		// 获取当日打卡列表
		var data = {
			id: this.data.gwInfo.id,
			rulesType:this.data.workBcIndex
		}
		var that = this;

		http.queryMyClockInList(data,
			function (res) {
				if (res.status == 200) {
					let data = { ...res.obj };
					let disabled = false;
					let workStartType = 0;
					let workEndType = 0;
					if (data.clockInList.length > 0) { 
						data.clockInList.map(item => { 
							let createTime=  item.createTime.replace(/-/g, '/')
							item.dktime = util.getHHMM(createTime);
							if (item.clockType == 1) {
								workStartType = 1
							} else if (item.clockType == 2) { 
								workEndType = 1
							}
						})
					}
					if (data.clockInList.length > 1) { 
						let start = new Date('2025/02/01 ' + data.clockInList[0].dktime).getTime();  // 实际上班打卡时间
						let end = new Date('2025/02/01 ' + data.clockInList[1].dktime).getTime(); // 实际下班打卡时间
						let type = 1;  //  1 固定考勤  2 打卡考勤
						let time = null;
						let a = '2025/02/01 ' + that.data.dkrule[that.data.workBcIndex].startWorkTime;   // 固定上班打卡时间
						let b = '2025/02/01 ' + that.data.dkrule[that.data.workBcIndex].endWorkTime;   // 固定下班打卡时间
						let atime = new Date(a).getTime()
						let btime = new Date(b).getTime()
						if (start > end) {
							// 夜班
							let qian = '2025/02/01 '+data.clockInList[0].dktime;// 前一天上班时间
							let hou = '2025/02/02 '+data.clockInList[1].dktime;// 前一天上班时间
							time = util.timeDifference(qian,hou)
						} else if (start < end) {
							// 白班
							let qian = '2025/02/01 '+data.clockInList[0].dktime;// 前一天上班时间
							let hou = '2025/02/01 '+data.clockInList[1].dktime;// 前一天上班时间
							time = util.timeDifference(qian,hou)
						}
						data.time = time
					}
					
					that.setData({
						dataList: data,
						workStartType,
						workEndType
					})
				} else {
					wx.showToast({
						title: res.message,
						icon: "none",
					})
				}
			},
			function (err) {
				wx.hideLoading()
			})
	},
	//在Page({})中使用下列代码
	//触发表单提交事件，调用接口
	formSubmit(e) {
		// 通过当前经纬度 解析 地址
		var that = this;
		wx.showLoading({
			title: '定位中...',
		})
		qqmapsdk.reverseGeocoder({
			location:that.data.latitude+','+that.data.longitude,
			coord_type: 5,
			get_poi:1,
			success: function (res) { //成功后的回调
				let info = res.result;
				wx.hideLoading({
					success: (res) => {},
				})
				var data = {
					address: info.address,
					lat: info.location.lat,
					lng: info.location.lng,
				}
				that.setData({
					lInfo: data,
				})
				let inArea = false;
				if (that.data.dkrule[that.data.workBcIndex].areaMode!=0) {
					that.data.dkrule[that.data.workBcIndex].positionList.map(item => { 
						if (!inArea) { 
							let position = item.position.split('|');
							let arr = [];
							for (let i = 0; i < position.length; i++) { 
								let a = position[i].split(',');
								// arr.push(a[1]+','+a[0])
								arr.push({
									latitude: a[1],
									longitude:a[0]
								})
							}
							inArea = that.checkIsPtInPoly(arr);
						}
					})
				} else { 
					inArea = that.checkdw()
				}
				wx.nextTick(_ => {
					if (!inArea) { 
						console.log(999)
						that.setData({
							reddk: that.data.reddk==0 ? '2' : 3
						})
					}
				})
			},
			fail: function (error) {
				wx.hideLoading({
					success: (res) => {},
				})
			},
			complete: function (res) {
				wx.hideLoading({
					success: (res) => {},
				})
			}
		})
	},

	getLocation: function () {
		let that = this;
		wx.getLocation({
			type: 'gcj02',
			isHighAccuracy: true,
			success: function (res) {
				that.data.latitude = res.latitude;
				that.data.longitude = res.longitude;
				that.formSubmit()
			},
			file(err) {
			 }
		})
	},



	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	uploadFlie: function (src, index) {
		var data = {
			url: src,
			name: "file",
			formData: {},
		}
		var that = this;
		wx.showLoading({
			title: '上传中...',
		})
		http.uploadFlie(data,
			function (res) {
				wx.hideLoading()
				if (res.code == 0) {
					that.data.imgStr.push(res.data);
					if (index == that.data.imgList.length - 1) {
						that.subclockIn();
					} else {
						that.uploadFlie(that.data.imgList[index + 1], index + 1)
					}
				} else {
					wx.showToast({
						title: res.message,
						icon: "none",
					})
				}
			},
			function (err) {
				wx.hideLoading()
			})


	},
	dkLz() {
		var that = this;
		http.getclockInInfo(this.data.gwInfo.id,
			function (res) {

			},
			function (err) {
				wx.hideLoading()
			})
	},
	//开始打卡
	subclockIn: function () {
		if (this.data.dkrule[this.data.workBcIndex].photo&&this.data.imgList.length==0) { 
			this.onclickPz()
			return false;
		}
		if (this.data.dkrule[this.data.workBcIndex].photo && this.data.imgList.length != 0 &&this.data.imgStr.length==0) { 
			this.uploadFlie(this.data.imgList[0], 0);
			return false;
		}
		
		var mode = 2
		var that = this;
		if (that.data.imgStr.length > 0) {
			mode = 1
		}
		if (!that.data.lInfo.lng) {
			wx.showToast({
				title: '无法获取您的位置微信，暂无法打卡，请点击重新定位后再次打卡',
				icon: "none",
			})
			return
		}
		var anomaly = this.data.reddk;
		// var data = {
		// 	"type": that.data.gwInfo.type, // 1 到达现场打卡 2 工作打卡 3 完成打卡
		// 	"lat": that.data.lInfo.lat, // 打卡位置 维度
		// 	"lng": that.data.lInfo.lng, // 打卡位置 经度
		// 	"address": that.data.lInfo.address, // 打卡位置
		// 	"mode": mode, // 1 拍照打卡 2 直接打卡
		// 	"imagePath": that.data.imgStr.join(","), // (可选) 照片地址，拍照打卡必须传递,
		// 	"anomaly": anomaly, //打卡状态
		// }
		var data = {
			"type": 2, // 1 到达现场打卡 2 工作打卡 3 完成打卡
			"lat":  that.data.lInfo.lat, // 打卡位置 维度
			"lng": that.data.lInfo.lng, // 打卡位置 经度
			"address": that.data.lInfo.address, // 打卡位置
			"mode": mode, // 1 拍照打卡 2 直接打卡
			"imagePath": that.data.imgStr.join(","), // (可选) 照片地址，拍照打卡必须传递,
			"anomaly": anomaly, //打卡状态
			rulesType: this.data.workBcIndex,
			clockType:this.data.dkworktype
		}
		var that = this;
		http.clockInNew(this.data.gwInfo.id, data,
			function (res) {
				if (res.code == 0) {
					wx.showToast({
						title: '打卡成功',
						icon: "none",
						duration: 5000
					})
					that.setData({
						imgList: [],
						imgStr:[]
					})
					if (that.data.gwInfo.type == 3) {
						that.dkLz()
						wx.showModal({
							title: "提示",
							content: "您已完成该工作，请等待工资结算",
							showCancel: false,
							confirmText: "我知道",
							success: function (res) {
								if (res.confirm) {
									wx.navigateBack({
										delta: 2,
									})
								}
							}
						})
					}
					if (that.data.gwInfo.type == 1) {
						wx.showToast({
							title: '打卡成功',
							icon: "none",
						})
						var info = that.data.gwInfo;
						wx.setNavigationBarTitle({
							title: "工作打卡",
						})
						info.type = 2;
						that.setData({
							gwInfo: info,
						})
						wx.setNavigationBarTitle({
							title: '工作打卡',
						})
					} else {
						wx.showToast({
							title: '打卡成功',
							icon: "none",
						})
					}
					that.getclockInList();
				} else {
					wx.showToast({
						title: res.message,
						icon: "none",
					})
				}
			},
			function (err) {
				wx.hideLoading()
			})

	},
	onclickDk: function () {
		// 异常判断
		var _this = this;
		let str = "";
		if (!this.data.disabled) { 
			return false;
		}
		if (this.data.reddk == 1) { 
			str='时间异常，'
		}
		if (this.data.reddk == 2) { 
			str='地点异常，'
		}
		if (this.data.reddk == 3) { 
			str='时间、地点均异常，'
		}
		if (this.data.reddk == 4) { 
			wx.showToast({
				title: '不在打卡规则范围内',
				icon:"none"
			})
			return false;
		}
		wx.showModal({
			title: '打卡',
			content: str + '确认打卡？',
			cancelText: '取消',
			confirmText: '确定',
			success(res) {
				if (res.confirm) { 
					_this.subclockIn()
				}
			 }
		  
		})
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		setTimeout(_ => { 
			if (this.data.imgList.length > 0) { 
				this.subclockIn()
			}
		},300)
		
	},
	onclickscp: function (e) {
		let src = e.currentTarget.dataset.src;
		wx.previewImage({
			current: src,
			urls: this.data.imgList,
		})
	},
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		clearInterval(timeid)
	},
	checkdw() {
		// 判断定位是否在区域呢
		var _this = this;
		let area = false;
		//调用距离计算接口
		qqmapsdk.calculateDistance({
			mode: 'straight', //可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
			//from参数不填默认当前地址
			//获取表单提交的经纬度并设置from和to参数（示例为string格式）
			from: _this.data.lInfo.lat+','+_this.data.lInfo.lng, //若起点有数据则采用起点坐标，若为空默认当前地址
			to: _this.data.dkrule[_this.data.workBcIndex].positionList[0].position, //终点坐标
			success: function (res) { //成功后的回调
				if (res.result.elements[0].distance < _this.data.dkrule[_this.data.workBcIndex].positionList[0].distance) {
					area = true;
				} else { 
					area= false;
				}
			},
			fail: function (error) {
			},
			complete: function (res) {
			}
		});
		return area;
	},
	checktime() {
		// 判断  当前时间 是否在打卡时间范围内
		let now = new Date().getTime();
		let a= util.formatTimexg(new Date()) + ' ' + this.data.dkrule[this.data.workBcIndex].startWorkTime
		let b = util.formatTimexg(new Date()) + ' ' + this.data.dkrule[this.data.workBcIndex].endWorkTime
		// let a= util.formatTime(new Date()) + ' 14:30'
		// let b= util.formatTime(new Date()) + ' 17:30'
		let start = new Date(a).getTime();
		let end = new Date(b).getTime();
		let errortime = 60 * 1000 * 30;
		let reddk = this.data.reddk;
		
		let disabled = this.data.disabled;
		let dktext = this.data.dktext;
		if (now > (start - errortime) && now < (start + errortime)) {
			this.data.dkworktype = 1;
			disabled = true;
			if (now > start && now < start + errortime) {
				dktext = '迟到打卡'
				reddk = reddk==0?1:3
			}
		} else if ((now > end - errortime) && (now < end + errortime)) {
			this.data.dkworktype = 2;
			disabled = true;
			if (now < end && now > end - errortime) {
				dktext = '早退打卡'
				reddk = reddk==0?1:3
			}
		} else { 
			reddk=reddk==0?1:4
		}
		console.log(1111,reddk)
		this.setData({
			disabled: disabled,
			dktext,
			reddk: reddk
		})
	},
	checkIsPtInPoly(latlngArr) {
		// 判断经纬度是否在 区域内
		if (util.isPtInPoly(this.data.latitude, this.data.longitude, latlngArr)) {
			return true
		}
		return false;
	},
	workBcCh(e) {
		if (this.data.dkrule.length > 1) { 
			this.setData({
				workBcIndex: e.detail.value,
				reddk: 0,
				disabled: false,
				dktext:'打卡'
			});
			this.checktime();
			this.getclockInList();
			this.formSubmit()
		}
	},
	getRule() {
		let params = {
			jobId:this.data.gwInfo.jobId*1
		}
		http.queryRulesInfo(params, res => {
			if (res.status == 200) { 
				this.setData({
					dkrule:res.obj
				})
				this.checktime()
				this.getclockInList()
			}
		}, err => {
		})
	},
	torule() {
		wx.navigateTo({
		  url: '/pages/clock/pages/dkrule/index?data='+this.data.copyData+'&workindex='+this.data.workBcIndex,
		})
	 }

})